package com.hmall.common.config;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.*;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(value = "spring.rabbitmq.listener.simple.retry.enabled",havingValue = "true")
@RequiredArgsConstructor
public class MqConsumeErrorAutoConfiguration {

    //声明一个动态的队列，用于接收错误消息，动态获取配置文件中的属性，注入到成员变量中去
    @Value("${spring.application.name}")
     private String QueueName;

    private final RabbitTemplate rabbitTemplate;


    //  - 声明一个交换机，名为error.direct，类型为direct
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange("error.direct");
    }

    //  - 声明一个队列，名为：微服务名 + error.queue，也就是说要动态获取
    // 2. 声明动态队列
    @Bean
    public Queue serviceErrorQueue(){
        return QueueBuilder.durable(QueueName + ".error.queue").build();
    }

    //  - 将队列与交换机绑定，绑定时的RoutingKey就是微服务名
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(serviceErrorQueue()).to(exchange()).with(QueueName);
    }

    //  - 声明RepublishMessageRecoverer，消费失败消息投递到上述交换机
    @Bean
    public RepublishMessageRecoverer republishMessageRecoverer() {
        return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", QueueName);
    }

}
